﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Java.Lang;
using Java.Net;

namespace PCControl
{
    class AquilaWolLibrary
    {
        public static void WakeUp(string mac)
        {
            WakeUp(mac, "255.255.255.255");
        }

        public static void WakeUp(string mac, string network)
        {
            WakeUp(mac, network, 9);
        }

        public static void WakeUp(string mac, string network, int udpPort)
        {
            WakeUp(mac, network, udpPort, 128);
        }

        ///
        public static void WakeUp(string mac, string network, int udpPort, int ttl)
        {

            // Android 4.0 之后不能在主线程中请求HTTP请求
            new Thread(delegate
            {
                MulticastSocket client = null;
                byte[] packet = new byte[17 * 6];
                byte[] macBytes;
                try
                {
                    macBytes = GetMac(mac);
                    for (int i = 0; i < 6; i++)
                    {
                        packet[i] = (byte)0xFF;
                    }
                    for (int i = 0; i < 16; i++)
                    {
                        for (int j = 0; j < 6; j++)
                        {
                            packet[(i + 1) * 6 + j] = macBytes[j];
                        }
                    }
                    client = new MulticastSocket();
                    InetAddress address = InetAddress.GetByName(network);
                    DatagramPacket datagramPacket = new DatagramPacket(packet, 0, packet.Length, address, udpPort);
                    client.TimeToLive = ttl;
                    client.Send(datagramPacket);
                    client.Close();
                }
                catch (Java.Lang.Exception ex)
                {
                    ex.PrintStackTrace();
                }
            }).Start();


        }

        private static byte[] GetMac(string mac)
        {
            byte[] m = new byte[6];
            string s;
            s = mac.Replace(" ", "");
            s = s.Replace(":", "");
            s = s.Replace("-", "");
            for (int i = 0; i < 6; i++)
            {
                string t = s.Substring(i * 2, 2);
                m[i] = (byte)Integer.ValueOf(t, 16).ByteValue();
            }
            return m;
        }
    }
}